package com.lottery.material.plugin;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

import com.lottery.material.util.CalendarUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;


/**
 * 时间处理类
 * @Author jy
 */
@Intercepts({@Signature(type= ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class DatePlugin implements Interceptor {


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (result != null) {
            if (result instanceof List) {
                List resultList = (List) result;
                for (int i = 0; i < resultList.size(); i++) {
                    Object o =  resultList.get(i);
                    if(Objects.nonNull(o)){
                        if(o.getClass().toString().contains("com.lottery.material.vo.portal")){
                            setCreateTime(o);
                        }
                    }
                }
            }else{
                if(result.getClass().toString().contains("com.lottery.material.vo.portal")){
                    setCreateTime(result);
                }
            }
        }
        return result;
    }

    private void setCreateTime(Object result) throws IllegalAccessException, ParseException {
        Field[] declaredFields = result.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            if(field.getName().equals("createTime")){
                field.setAccessible(true);
                String createTime = (String)field.get(result);
                // 判断是否为空
                if(StringUtils.isNotBlank(createTime)) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time = CalendarUtil.showTime(df.parse(createTime),"yyyy-MM-dd HH:mm:ss");
                    field.set(result,time);
                }
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }


}